<template>
  <div>
    <el-tabs v-model="activeTab">
      <el-tab-pane
        v-for="(value, key) in tabList"
        :key="key"
        :label="value"
        :name="key"
      >
        <el-form
          v-if="activeTab === key"
          ref="refForm"
          :model="formData"
          label-position="top"
        >
          <el-form-item v-show="activeTab === 'BASE'" label="节点Key" prop="id">
            <span class="b">{{ formData.id }}</span>
          </el-form-item>
          <el-form-item
            v-show="activeTab === 'BASE'"
            label="节点名称"
            prop="name"
            :rules="[
              {
                required: !isSequenceFlow,
                message: '请输入节点名称',
                trigger: 'change',
              },
            ]"
          >
            <el-input
              :disabled="!processCanEdit"
              v-model="formData.name"
              clearable
            />
          </el-form-item>

          <el-form-item v-show="activeTab === 'BASE'" label="节点描述">
            <el-input
              :disabled="!processCanEdit"
              v-model="formData.documentation"
              :rows="3"
              type="textarea"
              clearable
            />
          </el-form-item>

          <el-form-item
            v-if="!!showConfig.scriptSelect && activeTab === 'BASE'"
            label="执行脚本"
            prop="scriptId"
            :rules="[
              { required: true, message: '请选择执行脚本', trigger: 'change' },
            ]"
          >
            <template slot="label">
              执行脚本
              <el-button
                v-if="!!formData.scriptId"
                style="margin-left: 10px; font-size: 14px"
                type="text"
                @click="handleDebugScript()"
                >调试
              </el-button>
            </template>
            <tree-select
              :disabled="!processCanEdit"
              v-model="formData.scriptId"
              filterable
              :fieldMap="{
                value: 'id',
                label: 'name',
                disabled: 'disabled',
              }"
              :filterNodeMethod="filterNodeMethod"
              :treeData="scriptList"
            />
          </el-form-item>

          <template v-if="!!showConfig.httpService && activeTab === 'BASE'">
            <el-form-item label="服务" style="margin-bottom: 0" required>
              <el-row type="flex" align="middle">
                <el-form-item
                  class="service-task_http-service"
                  label=""
                  label-width="0px"
                  prop="httpServiceId"
                  :rules="[
                    {
                      required: true,
                      message: '请选择第三方服务',
                      trigger: 'change',
                    },
                  ]"
                >
                  <el-select
                    :disabled="!processCanEdit"
                    class="pct100"
                    v-model="formData.httpServiceId"
                    placeholder="请选择第三方服务"
                  >
                    <el-option
                      v-for="item in httpServiceList"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item
                  class="service-task_service-path"
                  label=""
                  label-width="0px"
                  prop="httpServicePath"
                  :rules="[
                    {
                      required: true,
                      message: '路径不能为空',
                      trigger: 'change',
                    },
                  ]"
                >
                  <el-input
                    :disabled="!processCanEdit"
                    v-model="formData.httpServicePath"
                    placeholder="请输入路径，以“/”开头"
                    :maxlength="128"
                    show-word-limit
                  >
                  </el-input>
                </el-form-item>
              </el-row>
            </el-form-item>

            <el-form-item label="自定义参数">
              <template slot="label">
                <span class="mr20">自定义参数</span>
                <el-button
                  :disabled="!processCanEdit"
                  type="text"
                  @click="handlehttpServiceParamsAdd"
                >
                  <i class="el-icon-edit"></i>
                  {{ !httpServiceParamsEmpty ? "编辑参数" : "添加参数" }}
                </el-button>
              </template>
              <JsonView
                v-if="!httpServiceParamsEmpty"
                :data="JSON.parse(formData.httpServiceParams)"
                :closed="false"
                :line-height="24"
                :showQuote="false"
              >
                <i class="el-icon-circle-plus-outline" slot="closedIcon" />
                <i class="el-icon-remove-outline" slot="openedIcon" />
              </JsonView>
            </el-form-item>
          </template>
          <!--     用戶任务模式-->
          <template>
            <el-form-item
              v-show="!!showConfig.userSetting && activeTab === 'BASE'"
              label="任务模式"
              prop="userTaskType"
              :rules="[
                {
                  required: true,
                  message: '请选择任务模式',
                  trigger: 'change',
                },
              ]"
            >
              <el-radio-group
                :disabled="!processCanEdit"
                v-model="formData.userTaskType"
                @change="handleUserTaskTypeChange"
              >
                <el-radio
                  class="mb5 mt5"
                  v-for="(value, key) in USER_TASK_TYPE_ENUM"
                  :key="key"
                  :label="key"
                  >{{ value }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              class="condition-item"
              prop="completionCondition"
              v-if="
                !!showConfig.userSetting &&
                activeTab === 'BASE' &&
                (formData.userTaskType === '1' || formData.userTaskType === '2')
              "
              label-width="0px"
              :rules="[
                {
                  required:
                    formData.userTaskType === '1' ||
                    formData.completionConditionChecked,
                  message: '请输入终止条件',
                  trigger: 'change',
                },
                {
                  pattern: VARIABLE_BUILT_IN_REG,
                  message: '请输入有效的终止条件表达式',
                  trigger: 'change',
                },
              ]"
            >
              <template slot="label"
                >终止条件
                <el-tooltip
                  popper-class="custom-popper"
                  content="请使用JUEL表达式来配置"
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>

              <el-form-item
                style="display: inline-block"
                prop="completionConditionChecked"
              >
                <el-checkbox
                  :disabled="formData.userTaskType === '1'"
                  style="margin-left: 10px"
                  v-model="formData.completionConditionChecked"
                >
                </el-checkbox>
              </el-form-item>
              <el-input
                :disabled="
                  !processCanEdit || !formData.completionConditionChecked
                "
                v-model="formData.completionCondition"
                style="margin-left: 10px; width: calc(100% - 35px)"
                placeholder="示例：${variable=='VALUE'}"
                clearable
              />
            </el-form-item>
          </template>
          <template v-if="!!showConfig.userSetting && activeTab === 'BASE'">
            <el-form-item
              label="人员类型"
              prop="userSettingType"
              :rules="[
                {
                  required: true,
                  message: '请选择人员类型',
                  trigger: 'change',
                },
              ]"
            >
              <el-radio-group
                v-model="formData.userSettingType"
                @change="handleUserSettingTypeChange"
              >
                <el-radio
                  class="mb5 mt5"
                  v-for="(value, key) in USER_SETTING_TYPE_ENUM"
                  :key="key"
                  :label="key"
                  >{{ value }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </template>

          <!--      <el-form-item-->
          <!--        label="人员"-->
          <!--        v-if="formData.userSettingType === 'u'"-->
          <!--        prop="assignee"-->
          <!--        :rules="[{ required: true, message: '请选择人员', trigger: 'change' }]"-->
          <!--      >-->
          <!--        <div @click.stop="handleAssigneeSelect">-->
          <!--          <el-input-->
          <!--            readonly-->
          <!--            :value="formData.assigneeName"-->
          <!--            placeholder="请选择人员"-->
          <!--          />-->
          <!--        </div>-->
          <!--      </el-form-item>-->

          <el-form-item
            label="部门"
            v-show="formData.userSettingType === 'o' && activeTab === 'BASE'"
            prop="assignee"
            :rules="[
              { required: true, message: '请选择部门', trigger: 'change' },
            ]"
          >
            <tree-select
              width="400"
              v-model="formData.assignee"
              :treeData="orgTree"
              :disabledValue="'ReadOnly'"
              :fieldMap="{ disabled: 'accessLevel' }"
            />
          </el-form-item>

          <el-form-item
            label="用户组"
            v-show="formData.userSettingType === 'ug' && activeTab === 'BASE'"
            prop="assignee"
            :rules="[
              { required: true, message: '请选择用户组', trigger: 'change' },
            ]"
          >
            <tree-select
              width="400"
              v-model="formData.assignee"
              :treeData="userGroupTree"
            />
          </el-form-item>
          <el-form-item
            label="审批组"
            v-show="formData.userSettingType === 'ag' && activeTab === 'BASE'"
            prop="assignee"
            :rules="[
              { required: true, message: '请选择审批组', trigger: 'change' },
            ]"
          >
            <el-select style="width: 400px" v-model="formData.assignee">
              <el-option
                v-for="item in approveGroupList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="业务模型人员字段"
            v-show="
              ['mu', 'mil'].includes(formData.userSettingType) &&
              activeTab === 'BASE'
            "
            prop="assignee"
            :rules="[
              { required: true, message: '请选择人员字段', trigger: 'change' },
            ]"
          >
            <el-select
              :disabled="!processCanEdit"
              style="width: 100%"
              v-model="formData.assignee"
            >
              <el-option
                v-for="item in staffFields"
                :key="item.code"
                :value="item.code"
                :label="item.name"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="业务模型部门字段"
            v-show="formData.userSettingType === 'mou' && activeTab === 'BASE'"
            prop="assignee"
            :rules="[
              { required: true, message: '请选择部门字段', trigger: 'change' },
            ]"
          >
            <el-select
              :disabled="!processCanEdit"
              style="width: 100%"
              v-model="formData.assignee"
            >
              <el-option
                v-for="item in deptFields"
                :key="item.code"
                :value="item.code"
                :label="item.name"
              />
            </el-select>
          </el-form-item>

          <!--      人员  多选-->
          <el-form-item
            label="人员"
            v-show="formData.userSettingType === 'u' && activeTab === 'BASE'"
            prop="assignee"
            :rules="[
              { required: true, message: '请选择人员', trigger: 'change' },
            ]"
          >
            <div @click.stop="handleCandidateUsersSelect">
              <el-input
                readonly
                :value="formData.candidateUserNames"
                placeholder="请选择人员"
              />
            </div>
          </el-form-item>

          <!--      人员  指定角色-->
          <el-form-item
            label="角色"
            v-show="formData.userSettingType === 'r' && activeTab === 'BASE'"
            prop="assignee"
            :rules="[
              { required: true, message: '请选择角色', trigger: 'change' },
            ]"
          >
            <el-select
              style="width: 400px"
              v-model="formData.assignee">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="人员脚本"
            v-if="formData.userSettingType === 'us' && activeTab === 'BASE'"
            prop="assignee"
            :rules="[
              { required: true, message: '请选择脚本', trigger: 'change' },
            ]"
          >
            <template slot="label">
              人员脚本
              <el-button
                v-if="!!formData.assignee"
                style="margin-left: 10px; font-size: 14px"
                type="text"
                @click="handleDebugScriptByCode(formData.assignee)"
                >调试
              </el-button>
            </template>
            <tree-select
              v-model="formData.assignee"
              filterable
              :fieldMap="{
                value: 'code',
                label: 'name',
                disabled: 'disabled',
              }"
              :filterNodeMethod="filterNodeMethod"
              :treeData="scriptList"
            />
          </el-form-item>

          <!--表单-->

          <el-form-item
            class="custome-set-required"
            prop="checkForm"
            v-if="!!showConfig.formKey && activeTab === 'FORM'"
            :rules="[{ validator: formKeyValidator, trigger: 'change' }]"
          >
            <template slot="label">

              <span class="dib" style="width: 340px">待办表单</span>
              <el-button size="medium" type="text" @click="configParam('todoParams')">
                <i v-if="formData.todoParams" class="el-icon-circle-check"></i>
                参数配置
              </el-button>
            </template>
            <el-form-item v-if="!!showConfig.formKey" prop="formKey">
              <template slot="label">
                <span class="mr10">PC</span>
                <el-button type="text" @click="preview('PC', formData.formKey)"
                ><i class="el-icon-view"></i>
                </el-button>
              </template>
              <tree-select
                clearable
                :disabled="!processCanEdit"
                v-model="formData.formKey"
                style="width: 100%"
                filterable
                :fieldMap="{
                  value: '__formKey__',
                  label: 'name',
                  disabled: 'disabled',
                }"
                :filterNodeMethod="filterNodeMethod"
                :treeData="pageList"
              />
            </el-form-item>
            <el-form-item label="APP" prop="appFormKey">
              <tree-select
                clearable
                :disabled="!processCanEdit"
                v-model="formData.appFormKey"
                style="width: 100%"
                filterable
                :fieldMap="{
                  value: '__formKey__',
                  label: 'name',
                  disabled: 'disabled',
                }"
                :filterNodeMethod="filterNodeMethod"
                :treeData="appPageList"
              />
            </el-form-item>
          </el-form-item>

          <el-form-item
            class="custome-set-required"
            prop="checkView"
            v-if="!!showConfig.formView && activeTab === 'FORM'"
            :rules="[{ validator: formViewValidator, trigger: 'change' }]"
          >
            <template slot="label">
              <span class="dib" style="width: 340px">查看表单</span>
              <el-button size="medium" type="text" @click="configParam('viewParams')"
              >
                <!--                todo 发布后还能配置吗-->
                <!--                <i class="el-icon-circle-check"></i>-->
                参数配置
              </el-button>
            </template>
            <el-form-item
              v-if="!!showConfig.formView && activeTab === 'FORM'"
              label="PC"
              prop="formView"
              :rules="[]"
            >
              <template slot="label">
                <span class="mr10">PC</span>
                <el-button type="text" @click="preview('PC', formData.formView)"
                ><i class="el-icon-view"></i
                ></el-button>
              </template>
              <tree-select
                :disabled="!processCanEdit"
                v-model="formData.formView"
                style="width: 100%"
                clearable
                filterable
                :fieldMap="{
                  value: 'key',
                  label: 'name',
                  disabled: 'disabled',
                }"
                :filterNodeMethod="filterNodeMethod"
                :treeData="pageList"
              />
            </el-form-item>
            <el-form-item
              v-if="!!showConfig.formView"
              label="APP"
              prop="appFormView"
              :rules="[
                // { required: true, message: '请选择查看表单', trigger: 'change' },
              ]"
            >
              <tree-select
                :disabled="!processCanEdit"
                v-model="formData.appFormView"
                style="width: 100%"
                filterable
                clearable
                :fieldMap="{
                  value: 'key',
                  label: 'name',
                  disabled: 'disabled',
                }"
                :filterNodeMethod="filterNodeMethod"
                :treeData="appPageList"
              />
            </el-form-item>
          </el-form-item>

          <template
            v-if="
              !!showConfig.conditionExpression &&
              showConditionExpression &&
              activeTab === 'BASE'
            "
          >
            <el-form-item
              label="流转条件"
              prop="conditionExpression"
              :rules="[
                {
                  required: true,
                  message: '请输入流转条件',
                  trigger: 'change',
                },
                {
                  pattern: VARIABLE_BUILT_IN_REG,
                  message: '请输入有效的流转条件表达式',
                  trigger: 'change',
                },
              ]"
            >
              <el-input
                :disabled="!processCanEdit"
                v-model="formData.conditionExpression"
                placeholder="示例：${variable=='VALUE'}"
                clearable
              />
            </el-form-item>
          </template>

          <el-form-item
            v-if="showPriority && activeTab === 'BASE'"
            label="优先级"
            prop="priority"
            :rules="[
              { required: true, message: '请输入优先级', trigger: 'change' },
              {
                pattern: POSITIVE_INTEGER_REG,
                message: '请输入正整数',
                trigger: 'change',
              },
            ]"
          >
            <el-input
              :disabled="!processCanEdit"
              v-model="formData.priority"
              clearable
              :maxlength="2"
            />
          </el-form-item>
          <!--通知-->
          <el-form-item
            prop="noticeTodoKey"
            v-if="!!showConfig.userSetting && activeTab === 'NOTICE'"
            label="待办通知"
          >
            <el-select
              style="width: 100%"
              v-model="formData.noticeTodoKey"
              clearable
              filterable
            >
              <el-option
                v-for="item in msgTemplateList"
                :key="item.code"
                :value="item.code"
                :label="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="!!showConfig.userSetting && activeTab === 'NOTICE'"
            label="超时通知"
          >
          </el-form-item>

          <el-form-item
            v-if="!!showConfig.userSetting && activeTab === 'NOTICE'"
            label="超时时间"
            style="display: inline-block; width: 50%; margin-right: 12px"
          >
            <el-input-number
              style="width: 100%"
              v-model="formData.overdueTime"
              controls-position="right"
              :min="1"
              :max="maxTime"
              :precision="0"
            />
          </el-form-item>
          <el-form-item
            v-if="!!showConfig.userSetting && activeTab === 'NOTICE'"
            :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }"
          >
            <el-select v-model="formData.timeoutUnit" style="width: 100%">
              <el-option value="day" label="天"></el-option>
              <el-option value="hour" label="小时"></el-option>
              <el-option value="min" label="分"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            prop="noticeUpgradeKey"
            v-if="!!showConfig.userSetting && activeTab === 'NOTICE'"
            label="升级规则"
          >
            <el-select
              style="width: 100%"
              v-model="formData.noticeUpgradeKey"
              clearable
              filterable
            >
              <el-option
                v-for="item in msgUpgradeTempList"
                :key="item.code"
                :value="item.code"
                :label="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="msgTemplate"
            v-if="!!showConfig.userSetting && activeTab === 'NOTICE'"
            label="升级通知"
          >
            <el-select
              style="width: 100%"
              v-model="formData.msgTemplate"
              clearable
              filterable
            >
              <el-option
                v-for="item in msgTemplateList"
                :key="item.code"
                :value="item.code"
                :label="item.code"
              />
            </el-select>
          </el-form-item>

          <template v-if="activeTab === 'EVENT'">
            <el-form-item prop="create_listener_script_id" label="节点进入前">
              <template slot="label">
                节点进入前
                <el-button
                  v-if="!!formData.create_listener_script_id"
                  style="margin-left: 10px; font-size: 14px"
                  type="text"
                  @click="
                    handleDebugScriptByCode(formData.create_listener_script_id)
                  "
                  >调试
                </el-button>
              </template>
              <tree-select
                :disabled="!processCanEdit"
                v-model="formData.create_listener_script_id"
                filterable
                clearable
                :fieldMap="{
                  value: 'code',
                  label: 'name',
                  disabled: 'disabled',
                }"
                :filterNodeMethod="filterNodeMethod"
                :treeData="scriptList"
              />
            </el-form-item>
            <el-form-item prop="create_listener_script_id" label="节点离开前">
              <template slot="label">
                节点离开前
                <el-button
                  v-if="!!formData.complete_listener_script_id"
                  style="margin-left: 10px; font-size: 14px"
                  type="text"
                  @click="
                    handleDebugScriptByCode(
                      formData.complete_listener_script_id
                    )
                  "
                  >调试
                </el-button>
              </template>
              <tree-select
                clearable
                :disabled="!processCanEdit"
                v-model="formData.complete_listener_script_id"
                filterable
                :fieldMap="{
                  value: 'code',
                  label: 'name',
                  disabled: 'disabled',
                }"
                :filterNodeMethod="filterNodeMethod"
                :treeData="scriptList"
              />
            </el-form-item>
          </template>

          <!-- <el-form-item v-if="!!showConfig.async" label="异步" prop="async">
            <el-switch v-model="formData.async"></el-switch>
          </el-form-item>

          <el-form-item v-if="!!showConfig.multiInstance" label="多实例">
            <el-badge :is-dot="hasMultiInstance">
              <el-button @click="multiInstanceDrawer = true">编辑</el-button>
            </el-badge>
          </el-form-item> -->

          <!-- <el-form-item v-if="!!showConfig.formKey" label="表单Key">
        <el-input v-model="formData.formKey" clearable/>
      </el-form-item> -->

          <!-- <el-form-item v-if="!!showConfig.buttons" label="按钮">
        <el-input v-model="formData.buttons" clearable/>
      </el-form-item> -->

          <!-- </el-collapse-item> -->

          <!-- <el-collapse-item v-if="!!showConfig.candidate" name="2">
          <template slot="title">
            <span class="el_title">候选配置<i class="header-icon el-icon-info"/></span>
          </template>

          <el-form-item v-if="!!showConfig.initiator" label="创建者" prop="initiator">
            <el-input v-model="formData.initiator" clearable/>
          </el-form-item>

          <el-form-item v-if="!!showConfig.assignee" label="执行人">
            <el-input v-model="formData.assignee" clearable/>
          </el-form-item>

          <el-form-item v-if="!!showConfig.candidateUsers" label="候选用户">
            <el-input v-model="formData.candidateUsers" clearable/>
          </el-form-item>
          <el-form-item v-if="!!showConfig.candidateGroups" label="候选组">
            <el-input v-model="formData.candidateGroups" clearable/>
          </el-form-item>

        </el-collapse-item> -->

          <!-- <el-collapse-item v-if="!!showConfig.form" name="3">
          <template slot="title">
            <span class="el_title">表单配置<i class="header-icon el-icon-info"/></span>
          </template>

          <el-form-item v-if="!!showConfig.formKey" label="表单Key">
            <el-input v-model="formData.formKey" clearable/>
          </el-form-item>

          <el-form-item v-if="!!showConfig.buttons" label="按钮">
            <el-input v-model="formData.buttons" clearable/>
          </el-form-item>

        </el-collapse-item> -->

          <!-- <el-collapse-item v-if="!!showConfig.listener" name="4">
          <template slot="title">
            <span class="el_title">监听器<i class="header-icon el-icon-info"/></span>
          </template>

          <el-form-item label="执行监听">
            <el-badge :value="executionListenerLength">
              <el-button @click="executionListenerDrawer = true">编辑</el-button>
            </el-badge>
          </el-form-item>

          <el-form-item v-if="!!showConfig.taskListener" label="任务监听">
            <el-badge :value="taskListenerLength">
              <el-button @click="taskListenerDrawer = true">编辑</el-button>
            </el-badge>
          </el-form-item>

        </el-collapse-item> -->

          <!-- </el-collapse> -->
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <multi-instance
      title="多实例"
      v-if="!!showConfig.multiInstance"
      :element="element"
      :modeler="modeler"
      @changeMultiInstanceDrawer="changeMultiInstanceDrawer"
      @saveMultiInstance="saveMultiInstance"
      :multiInstanceDrawer="multiInstanceDrawer"
    ></multi-instance>

    <listener
      title="执行监听"
      type="Execution"
      :element="element"
      :modeler="modeler"
      @changeListenerDrawer="changeExecutionListenerDrawer"
      @saveListener="saveExecutionListener"
      :listenerDrawer="executionListenerDrawer"
    ></listener>

    <listener
      title="任务监听"
      type="Task"
      :element="element"
      :modeler="modeler"
      @changeListenerDrawer="changeTaskListenerDrawer"
      @saveListener="saveTaskListener"
      :listenerDrawer="taskListenerDrawer"
    ></listener>

    <select-modal
      itemRadio
      title="选择人员"
      :autoClose="false"
      ref="SelectAssigneeModal"
      :treeData="orgTree"
      :treeNodeChange="handleSelectAssigneeNodeChange"
      @ok="handleAssigneeChange"
    >
    </select-modal>

    <select-modal
      title="选择人员"
      :autoClose="false"
      ref="SelectCandidateUsersModal"
      :treeData="orgTree"
      :treeNodeChange="handleSelectAssigneeNodeChange"
      @ok="handleCandidateUsersChange"
    >
    </select-modal>
    <ParamConfigModal
      ref="ParamConfigModal"
      :process-can-edit="processCanEdit"
      @ok="setParamConfig">
    </ParamConfigModal>
  </div>
</template>

<script>
import ParamConfigModal from "./ParamConfigModal";
import { arrayToTree } from "@/utils/util";
import { mapGetters } from "vuex";
import mixinPanel from "../mixins/mixinPanel";
import MultiInstance from "../properties/multiInstance";
import listener from "../properties/listener";
import lodash from "lodash";

import SelectModal from "@/components/SelectModal";
import { getFields, setFields } from "../utils/util";
import ScriptEditor from "@/components/ScriptEditor";
import JsonView from "@/components/JsonView";
import jsonFormat from "json-format";
import { VARIABLE_BUILT_IN_REG, POSITIVE_INTEGER_REG } from "@/utils/reg";

import {
  createScriptTreeNode,
  filterNodeMethod,
} from "@/utils/treeSelectFormat";

import { TAB_PROCESS_CONFIG_ENUM } from "@/utils/enum";

import { getHmorgListwithpermission } from "@/apis/paas/HmOrgController.js";
import { getHmusergroupList } from "@/apis/paas/HmUserGroupController.js";
import { getHmpagefolderListTree } from "@/apis/paas/HmPageFolderController.js";
import { getHmuserPageListwithpermission } from "@/apis/paas/HmUserController.js";
import { getHmentitymodelList } from "@/apis/paas/HmEntityModelController.js";
import { getHmhttpserviceList } from "@/apis/paas/HmHttpServiceController.js";
import { getHmapprovegroupList } from "@/apis/paas/HmApproveGroupController.js";
import { getHmscriptfolderListTree } from "@/apis/paas/HmScriptFolderController.js";
import { getMsgTemplateconfigPagelist } from "@/apis/paas/MsgTemplateConfigController.js";
import { getMsgUpgradenoticePagelist } from "@/apis/paas/UpgradeNoticeController.js";
import { getHmpageInfoKey } from "@/apis/paas/HmPageController.js";
import { getHmrolePageList } from '@/apis/paas/HmRoleController.js'
import DesignPreview from "@/components/DesignPreview/index.js";

const USER_TASK_TYPE_ENUM = {
  0: "竞签",
  1: "并签",
  2: "串签",
};
const USER_SETTING_TYPE_ENUM = {
  u: "指定人员",
  o: "部门负责人",
  // ug: "用户组",
  ag: "审批组",
  mu: "业务模型人员",
  mil: "直属上级",
  r: "指定角色",
  mou: "业务模型部门负责人",
  us: "人员脚本",
};
const defaultTab = Object.keys(TAB_PROCESS_CONFIG_ENUM)[0];
export default {
  name: "BpmnNode",
  components: {
    listener,
    MultiInstance,
    SelectModal,
    JsonView,
    ParamConfigModal
  },
  mixins: [mixinPanel],
  data() {
    return {
      tabList: [],
      activeTab: defaultTab,
      TAB_PROCESS_CONFIG_ENUM,
      filterNodeMethod,
      VARIABLE_BUILT_IN_REG,
      POSITIVE_INTEGER_REG,
      USER_TASK_TYPE_ENUM,
      USER_SETTING_TYPE_ENUM,
      formData: {
        userTaskType: 0,
      },

      activeName: "1",
      multiInstanceDrawer: false,
      hasMultiInstance: false,
      executionListenerDrawer: false,
      executionListenerLength: 0,
      taskListenerDrawer: false,
      taskListenerLength: 0,

      orgTree: [],
      userGroupTree: [],
      approveGroupList: [], // 审批组
      roleList: [],
      pageList: [],
      scriptList: [],
      httpServiceList: [],
      staffFields: [],
      deptFields: [],
      msgTemplateList: [],
      msgUpgradeTempList: [],
      appPageList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      modelList: [],
      modelListFlat: [],
    };
  },

  computed: {
    ...mapGetters(["processCanEdit"]),
    modelId() {
      const bizObj = this.element.businessObject.$parent;
      return getFields(bizObj).model;
    },
    maxTime() {
      switch (this.unit) {
        case "min":
          return 60 * 24 * 360;
        case "hour":
          return 24 * 360;
        case "day":
          return 360;
      }
    },

    /**
     * 业务服务 参数空
     */
    httpServiceParamsEmpty() {
      // const httpServiceParams = JSON.stringify(this.formData.httpServiceParams)
      const { httpServiceParams } = this.formData;
      return !httpServiceParams || httpServiceParams === "{}";
    },

    /**
     * 元素为流程线
     */
    isSequenceFlow() {
      return this.element.type === "bpmn:SequenceFlow";
    },

    /**
     * 需要流转条件的场景
     * 1.排他网关后的流程线
     */
    showConditionExpression() {
      if (
        this.isSequenceFlow &&
        this.element.businessObject.sourceRef.$type === "bpmn:ExclusiveGateway"
      ) {
        return true;
      }
      return false;
    },

    /**
     * 是否优先级
     * 排他网关后的节点
     */
    showPriority() {
      if (this.isSequenceFlow) {
        return false;
      }
      if (
        this.element.incoming.find(
          (flow) =>
            flow.businessObject.sourceRef.$type === "bpmn:ExclusiveGateway"
        )
      ) {
        return true;
      }
      return false;
    },
    processDisabled() {
      return this.element.elementCanConfig === false;
    },
  },

  watch: {
    "formData.initiator": function (val) {
      this.updateProperty("initiator", val, true);
    },
    "formData.category": function (val) {
      this.updateProperty("category", val, true);
    },

    "formData.async": function (val) {
      this.updateProperty("async", val, true);
    },

    /**
     * 排他网关流程 优先级
     */
    "formData.priority": function (val) {
      this.updateProperty("priority", val, true);
    },
    /**
     * 排他网关流程 表达式
     */
    "formData.conditionExpression": function (val) {
      if (val) {
        const newCondition = this.modeler
          .get("moddle")
          .create("bpmn:FormalExpression", { body: val });
        this.updateProperties({ conditionExpression: newCondition });
      } else {
        this.updateProperties({ conditionExpression: null });
      }
    },

    "formData.skipExpression": function (val) {
      this.updateProperty("skipExpression", val, true);
    },

    "formData.candidateUsers": function (val) {
      this.updateProperty("candidateUsers", val, true);
    },
    "formData.candidateGroups": function (val) {
      this.updateProperty("candidateGroups", val, true);
    },
    "formData.dueDate": function (val) {
      this.updateProperty("dueDate", val, true);
    },

    "formData.isForCompensation": function (val) {
      this.updateProperty("isForCompensation", val);
    },
    "formData.triggerable": function (val) {
      this.updateProperty("triggerable", val, true);
    },
    "formData.class": function (val) {
      this.updateProperty("class", val, true);
    },
    "formData.autoStoreVariables": function (val) {
      this.updateProperty("autoStoreVariables", val, true);
    },
    "formData.exclude": function (val) {
      this.updateProperty("exclude", val, true);
    },
    "formData.ruleVariablesInput": function (val) {
      this.updateProperty("ruleVariablesInput", val, true);
    },
    "formData.rules": function (val) {
      this.updateProperty("rules", val, true);
    },
    "formData.resultVariable": function (val) {
      this.updateProperty("resultVariable", val, true);
    },

    /**
     * 待办表单
     */
    "formData.formKey": function (val) {
      if (val) {
        this.$refs.refForm &&
          this.$refs.refForm[0] &&
          this.$refs.refForm[0].clearValidate("checkForm");
      }
      setFields(this.modeler, this.element, {
        formKey: val ? String(val) : "",
      });
      // this.updateProperty('formKey', val, true)
    },
    "formData.appFormKey": function (val) {
      if (val) {
        this.$refs.refForm &&
          this.$refs.refForm[0] &&
          this.$refs.refForm[0].clearValidate("checkForm");
      }
      // this.updateProperty('appFormKey', val, true)
      setFields(this.modeler, this.element, {
        appFormKey: val ? String(val) : "",
      });
    },
    /**
     * 查看表单
     */
    "formData.formView": function (val) {
      if (val) {
        this.$refs.refForm &&
          this.$refs.refForm[0] &&
          this.$refs.refForm[0].clearValidate("checkView");
      }
      setFields(this.modeler, this.element, {
        formView: val ? String(val) : "",
      });
    },
    "formData.appFormView": function (val) {
      if (val) {
        this.$refs.refForm &&
          this.$refs.refForm[0] &&
          this.$refs.refForm[0].clearValidate("checkView");
      }
      setFields(this.modeler, this.element, {
        appFormView: val ? String(val) : "",
      });
    },
    // 待办通知
    "formData.noticeTodoKey": function (val) {
      setFields(this.modeler, this.element, {
        noticeTodoKey: val ? String(val) : "",
      });
    },
    // 升级通知
    "formData.noticeUpgradeKey": function (val) {
      setFields(this.modeler, this.element, {
        noticeUpgradeKey: val ? String(val) : "",
      });
    },

    "formData.msgTemplate": function (val) {
      setFields(this.modeler, this.element, {
        msgTemplate: val ? String(val) : "",
      });
    },
    "formData.upgradeTimeout": function (val) {
      setFields(this.modeler, this.element, {
        upgradeTimeout: val ? String(val) : "",
      });
    },
    "formData.overdueTime": function (val) {
      this.formData.upgradeTimeout =
        this.formData.overdueTime + "_" + this.formData.timeoutUnit;
    },
    "formData.timeoutUnit": function (val) {
      this.formData.upgradeTimeout =
        this.formData.overdueTime + "_" + this.formData.timeoutUnit;
    },

    /**
     * 服务任务 服务ID
     */
    "formData.httpServiceId": function (val) {
      this.updateProperty(
        "class",
        "com.harmontronics.hanma.paas.paas.domain.app.service.ServiceTaskHttpSupportDelegate",
        true
      );
      setFields(this.modeler, this.element, {
        httpServiceId: val ? String(val) : "",
      });
    },
    /**
     * 服务任务 路径
     */
    "formData.httpServicePath": function (val) {
      setFields(this.modeler, this.element, {
        path: val ? String(val) : "",
      });
    },
    /**
     * 服务任务 参数
     */
    "formData.httpServiceParams": function (val) {
      const params = val || "{}";
      setFields(this.modeler, this.element, {
        params,
      });
    },

    /**
     * 脚本任务 执行脚本
     */
    "formData.scriptId": function (val) {
      this.updateProperty(
        "class",
        "com.harmontronics.hanma.paas.paas.service.script.ServiceTaskScriptSupportDelegate",
        true
      );
      setFields(this.modeler, this.element, {
        script: val ? String(val) : "",
      });
    },
    /**
     * 节点进入前
     */
    "formData.create_listener_script_id": function (val) {
      let extensionElements = this.element.businessObject.get(
        "extensionElements"
      );
      if (
        !extensionElements.values.find(
          (value) =>
            value.$type === "flowable:TaskListener" && value.event === "create"
        )
      ) {
        const listener = this.modeler
          .get("moddle")
          .create("flowable:TaskListener");
        listener["event"] = "create";
        listener["delegateExpression"] = "${userTaskCreationListener}";
        extensionElements.get("values").push(listener);
      }
      setFields(this.modeler, this.element, {
        create_listener_script_id: val ? String(val) : "",
      });
    },
    /**
     * 节点离开前
     */
    "formData.complete_listener_script_id": function (val) {
      let extensionElements = this.element.businessObject.get(
        "extensionElements"
      );
      if (
        !extensionElements.values.find(
          (value) =>
            value.$type === "flowable:TaskListener" &&
            value.event === "complete"
        )
      ) {
        const listener = this.modeler
          .get("moddle")
          .create("flowable:TaskListener");
        listener["event"] = "complete";
        listener["delegateExpression"] = "${userTaskCompletionListener}";
        extensionElements.get("values").push(listener);
      }
      setFields(this.modeler, this.element, {
        complete_listener_script_id: val ? String(val) : "",
      });
    },
    /**
     * 用户任务模式
     */
    "formData.userTaskType": function (val) {
      if (!val) return;
      const idFlag = this.element.id?.split("_")[1];
      let extensionElements = this.element.businessObject.get(
        "extensionElements"
      );

      if (!extensionElements) {
        // 创建元素
        extensionElements = this.modeler
          .get("moddle")
          .create("bpmn:ExtensionElements");
      }

      let loopCharacteristics = this.element.businessObject.loopCharacteristics;
      if (!loopCharacteristics) {
        loopCharacteristics = this.modeler
          .get("moddle")
          .create("bpmn:MultiInstanceLoopCharacteristics");
      }
      loopCharacteristics.set(
        this.descriptorPrefix + "elementVariable",
        "assignee"
      );
      loopCharacteristics.set(
        this.descriptorPrefix + "collection",
        `assigneeList_${idFlag}`
      );

      setFields(this.modeler, this.element, {
        userTaskType: val,
      });
      let completionCondition;
      // '0': '竞签', '1': '并签',  '2': '串签'
      if (val === "0") {
        loopCharacteristics.isSequential = "false";
        completionCondition = this.modeler
          .get("moddle")
          .create("bpmn:Expression", {
            body: "${nrOfCompletedInstances == 1}",
          });
        loopCharacteristics["completionCondition"] = completionCondition;
        this.$set(this.formData, "completionCondition", "");
        this.$set(this.formData, "completionConditionChecked", false);
      } else if (val === "1") {
        // 并签
        this.formData.completionConditionChecked = true;
        if (!this.formData.completionCondition) {
          this.$set(
            this.formData,
            "completionCondition",
            "${nrOfCompletedInstances == nrOfInstances}"
          );
        }
        this.$set(this.formData, "completionConditionChecked", true);
        loopCharacteristics.isSequential = "false";
        completionCondition = this.modeler
          .get("moddle")
          .create("bpmn:Expression", {
            body: this.formData.completionCondition,
          });
        loopCharacteristics["completionCondition"] = completionCondition;
      } else if (val === "2") {
        if (!this.formData.completionConditionChecked) {
          loopCharacteristics["completionCondition"] = undefined;
        }
        // 串签
        // const completionCondition = this.modeler
        //   .get("moddle")
        //   .create("bpmn:Expression", {
        //     body: "${complete_in_advance}",
        //   });
        loopCharacteristics.isSequential = true;
      }

      if (val) {
        this.updateProperties({ loopCharacteristics });
        this.updateProperty("assignee", "${assignee}", true);
      }
    },
    // 终止条件
    "formData.completionCondition": function (val) {
      if (this.formData.userTaskType !== "0") {
        const loopCharacteristics = this.element.businessObject
          .loopCharacteristics;
        const completionCondition = this.modeler
          .get("moddle")
          .create("bpmn:Expression", {
            body: val,
          });
        loopCharacteristics["completionCondition"] =
          completionCondition || undefined;
        // this.updateProperties({loopCharacteristics});
      }
    },
    "formData.completionConditionChecked": function (val) {
      if (!val) {
        this.$set(this.formData, "completionCondition", "");
      }
      setFields(this.modeler, this.element, {
        completionConditionChecked: val,
      });
    },

    /**
     * 用户任务 人员类型设置
     */
    "formData.userSettingType": function (val) {
      // this.updateProperty('assignee', '', true)
    },
    /**
     * 用户任务 人员设置具体值
     */
    "formData.assignee": function (val) {
      const {userSettingType, candidateUserNames} = this.formData;
      let extensionElements = this.element.businessObject.get(
        "extensionElements"
      );
      if (!extensionElements) {
        // 创建元素
        extensionElements = this.modeler
          .get("moddle")
          .create("bpmn:ExtensionElements");
      }
      let loopCharacteristics = this.element.businessObject.loopCharacteristics;
      if (!loopCharacteristics) {
        loopCharacteristics = this.modeler
          .get("moddle")
          .create("bpmn:MultiInstanceLoopCharacteristics");
      }
      if (userSettingType === "u") {
        let userArr = [];
        if (val === undefined) {
          userArr = [];
        } else if (val && val.indexOf(",") < -1) {
          userArr = [val];
        } else {
          if (!val.split) return
          val && (userArr = val.split(","));
        }
        const userStr = "u_" + userArr.join(",");
        setFields(this.modeler, this.element, {
          collectionString: userStr,
          userNames: candidateUserNames,
        });
      } else {
        if (extensionElements) {
          const list = extensionElements?.values || [];
          list.forEach((value, index) => {
            if (value.name === "userNames") {
              list.splice(index, 1);
            }
          });
          this.modeler.get("modeling").updateProperties(this.element, {
            extensionElements,
          });
        }
        setFields(this.modeler, this.element, {
          collectionString: val ? `${userSettingType}_${val}` : "",
        });
      }
    },
  },
  created() {
    this.init();
  },

  // mounted () {

  // },

  methods: {
    getModelIdByCode(code) {
      const model = this.modelListFlat.find((item) => item.code === code);
      return model?.id;
    },

    async init() {
      const data = {
        ...this.element.businessObject,
        ...this.element.businessObject.$attrs,
      };

      // 流程数据
      const globalBizObj = this.element.businessObject.$parent;
      const globalBizObjFields = getFields(globalBizObj);
      const {
        model,
        formKey: globalFormKey,
        appFormKey: globalAppFormKey,
        formView: globalFormView,
        appFormView: globalAppFormView,
      } = globalBizObjFields;

      const res = await this.$parent.modelPromise;
      this.modelList = res.tree;
      this.modelListFlat = res.list;
      const modelId = this.getModelIdByCode(
        /^\d+$/.test(model) ? this.modelData.modelCode : model
      );

      const loopCharacteristics = data.loopCharacteristics;
      if (modelId) {
        this.loadPageList(modelId, "ALL");
        this.loadPageList(modelId, "APP");
        this.loadMsgTemplate();
        this.loadMsgUpgradeTemplate();
        this.loadStaffFields(modelId);
      }

      // 节点数据
      const bizObj = this.element.businessObject;
      const bizObjFields = getFields(bizObj);
      const {
        script: scriptId,
        formKey,
        appFormKey,
        formView,
        appFormView,
        httpServiceId,
        path,
        params,
        collectionString, // assignee数据
        userNames, // 用户userNames
        userTaskType, // 任务模式
        // 通知
        noticeTodoKey,
        noticeUpgradeKey,
        msgTemplate,
        upgradeTimeout,
        completionConditionChecked,
        create_listener_script_id,
        complete_listener_script_id,
        todoParams,  //待办表单参数配置
        viewParams
      } = bizObjFields;

      // console.log('bizObjFields', bizObjFields)
      // console.log('showConfig', this.showConfig)

      const {showConfig} = this;
      if (showConfig.userSetting) {
        this.updateProperty("formKey", "formKey.form", true);
      }

      // 获取需要展示的tab
      this.getTabRes();
      if (showConfig.userSetting) {
        data.noticeTodoKey = noticeTodoKey; // 待办通知
        data.upgradeTimeout = upgradeTimeout; // 超时时间
        data.noticeUpgradeKey = noticeUpgradeKey; // 超时  升级规则
        data.msgTemplate = msgTemplate; // 超时  升级通知
        data.todoParams = todoParams // 参数配置
        data.viewParams = viewParams
      }
      if (data.upgradeTimeout) {
        data.overdueTime = Number(data.upgradeTimeout.split("_")[0]);
        data.timeoutUnit = data.upgradeTimeout.split("_")[1];
        if (data.timeoutUnit === 'undefined') {
          data.timeoutUnit = ''
        }
      }

      if (showConfig.userSetting && data.assignee) {
        if (userNames && userNames !== "undefined") {
          data.candidateUserNames = userNames;
        }
        const assigneeArr = collectionString ? collectionString.split("_") : [];
        data.userSettingType = assigneeArr[0] || "u";
        data.userTaskType = userTaskType || "0";
        if (["mu", "mou", "mil", "us"].includes(data.userSettingType)) {
          data.assignee = assigneeArr.slice(1).join("_");
        } else if (
          data.userSettingType === "u" &&
          assigneeArr.length &&
          assigneeArr[1]
        ) {
          data.assignee = assigneeArr[1]
            .split(",")
            .map((item) => {
              return Number(item);
            })
            .join(",");
        } else {
          data.assignee = assigneeArr[1] ? Number(assigneeArr[1]) : undefined;
        }
        // 终止条件处理  --- 并签必填，设置默认值，串签不必填
        if (
          loopCharacteristics?.completionCondition?.body &&
          data.userTaskType !== "0"
        ) {
          const body = loopCharacteristics?.completionCondition?.body;
          data.completionConditionChecked =
            completionConditionChecked === "true";
          data.completionCondition = body;
          body && (data.completionConditionChecked = true);
        } else {
          data.completionConditionChecked = false;
        }
      } else {
        data.userSettingType = undefined;
        data.assignee = undefined;
        data.assigneeName = undefined;
        // 默认用户任务是竞签和 人员类型指定人员
        if (showConfig.userSetting) {
          data.userTaskType = "0";
          data.userSettingType = "u";
        }
      }

      if (showConfig.httpService) {
        data.httpServiceId = httpServiceId ? Number(httpServiceId) : "";
        data.httpServicePath = path;
        data.httpServiceParams = params || "{}";
      }

      if (showConfig.scriptSelect && scriptId) {
        data.scriptId = Number(scriptId);
      }

      if (this.element.id === "__initiator__" || this.showConfig.userSetting) {
        data.noticeTodoKey = noticeTodoKey;
        if (!formKey && !appFormKey) {
          data.formKey = globalFormKey;
          data.appFormKey = globalAppFormKey;
        } else {
          data.formKey = formKey;
          data.appFormKey = appFormKey;
        }
        if (!formView && !appFormView) {
          data.formView = globalFormView;
          data.appFormView = globalAppFormView;
        } else {
          data.formView = formView;
          data.appFormView = appFormView;
        }
      }
      data.documentation = this.getDocumentation();
      data.priority = data.priority || data["flowable:priority"] || undefined;
      data.conditionExpression = this.element.businessObject.conditionExpression?.body;

      data.create_listener_script_id = create_listener_script_id;
      data.complete_listener_script_id = complete_listener_script_id;
      this.formData = data;

      this.hasMultiInstance = !!this.element.businessObject.loopCharacteristics;
      this.executionListenerLength =
        this.element.businessObject.extensionElements?.values?.filter(
          (item) => item.$type === this.descriptorPrefix + "ExecutionListener"
        ).length ?? 0;
      this.taskListenerLength =
        this.element.businessObject.extensionElements?.values?.filter(
          (item) => item.$type === this.descriptorPrefix + "TaskListener"
        ).length ?? 0;

      this.loadOrgData();
      this.loadUserGroupData();
      this.loadApproveGroupData();
      this.loadRoleList();
      this.loadHttpServiceList();
      this.loadScriptList();
    },

    // 表单预览
    async preview(type, pageKey) {
      if (!pageKey) {
        this.$message.info("请选择表单");
        return;
      }
      const { json, name } = await getHmpageInfoKey({
        key: pageKey,
        includeJson: true,
      });
      try {
        if (json) {
          const { FormData, formList } = JSON.parse(json);
          DesignPreview.openDrawer({
            hmpageInfo: FormData,
            formList,
            title: name,
          });
        } else {
          this.$message.info("表单未保存");
        }
      } catch (error) {
        console.log(error);
      }
    },
    /**
     * 加载部门数据
     */
    loadOrgData() {
      getHmorgListwithpermission().then((res) => {
        this.orgTree = arrayToTree(res);
      });
    },

    /**
     * 加载用户组数据
     */
    loadUserGroupData() {
      getHmusergroupList().then((res) => {
        this.userGroupTree = res;
      });
    },
    // 加载审批组数据
    loadApproveGroupData() {
      getHmapprovegroupList().then((res) => {
        this.approveGroupList = res;
      });
    },
    loadRoleList() {
      getHmrolePageList({
        pageSize: 100000,
        pageNo: 1,
        status: 1
      }).then((res) => {
        this.roleList = res.data;
      });
    },

    /**
     * 加载第三方服务数据
     */
    loadHttpServiceList() {
      getHmhttpserviceList().then((res) => {
        this.httpServiceList = res;
      });
    },

    /**
     * 加载所有表单页面
     */
    loadPageList(modelId, type) {
      getHmpagefolderListTree({
        modelId,
        type,
        // type: 'FORM',
        filterNonJson: true,
      }).then((res) => {
        res.forEach((node) => {
          node.type = "folder";
        });
        if (type === "ALL") {
          this.pageList = this.createPageTreeNode(res);
        } else if (type === "APP") {
          this.appPageList = this.createPageTreeNode(res);
        }
        // this.pageList = res.map((item) => {
        //   item.__formKey__ = `${item.key}.form`
        //   return item
        // })
      });
    },

    /**
     * 加载所有脚本
     */
    loadScriptList() {
      getHmscriptfolderListTree().then((res) => {
        res.forEach((node) => {
          node.type = "folder";
          node.code = node.id;
        });
        this.scriptList = createScriptTreeNode(res || []);
      });
    },
    /**
     * 加载消息模板
     */
    loadMsgTemplate() {
      getMsgTemplateconfigPagelist({ pageSize: 100000 }).then((res) => {
        this.msgTemplateList = res.data;
      });
    },
    loadMsgUpgradeTemplate() {
      getMsgUpgradenoticePagelist({ pageSize: 100000 }).then((res) => {
        this.msgUpgradeTempList = res.data;
      });
    },
    loadStaffFields(modelId) {
      getHmentitymodelList({
        modelId,
        activated: true,
      }).then((res) => {
        this.staffFields = res.filter(
          (item) => item.type === "STAFF" && item.code !== "assignee_"
        );
        this.deptFields = res.filter((item) => item.type === "DEPARTMENT");
      });
    },
    // 切换任务模式
    handleUserTaskTypeChange() {},
    // 切换人员类型
    handleUserSettingTypeChange() {
      this.$set(this.formData, "assignee", undefined);
      this.$set(this.formData, "assigneeName", undefined);
      this.$set(this.formData, "candidateUserNames", undefined);
    },

    handleAssigneeSelect() {
      this.$refs.SelectAssigneeModal.open();
    },

    handleAssigneeChange(data) {
      const { item } = data;
      if (item.length === 0) {
        this.$message.warning("请选择人员");
        return;
      }
      const { id, name } = item[0];
      this.$set(this.formData, "assignee", id);
      this.$set(this.formData, "assigneeName", name);
      this.$refs.SelectAssigneeModal.close();
    },

    handleSelectAssigneeNodeChange(org) {
      return getHmuserPageListwithpermission({
        pageSize: 100000,
        pageNo: 1,
        orgIds: org.id,
        status: 1,
      }).then((res) => {
        return res.data;
      });
    },

    handleCandidateUsersSelect() {
      const selectModel = this.$refs.SelectCandidateUsersModal;
      if (this.formData.assignee) {
        const ids = this.formData.assignee.split(",");
        const idList= ids.map((item) => Number(item));
        selectModel.open(idList);
        return
      }
      selectModel.open();
    },

    handleCandidateUsersChange(data) {
      const { item } = data;
      if (item.length === 0) {
        this.$message.warning("请选择人员");
        return;
      }
      const ids = item.map((ele) => ele.id).join(",");
      const names = item.map((ele) => ele.name).join(",");
      this.$set(this.formData, "assignee", ids);
      this.$set(this.formData, "candidateUserNames", names);
      this.$refs.SelectCandidateUsersModal.close();
    },

    changeMultiInstanceDrawer(v) {
      this.multiInstanceDrawer = v;
    },
    saveMultiInstance(v) {
      this.hasMultiInstance = v;
    },
    changeExecutionListenerDrawer(v) {
      this.executionListenerDrawer = v;
    },
    saveExecutionListener(v) {
      this.executionListenerLength = v;
    },
    changeTaskListenerDrawer(v) {
      this.taskListenerDrawer = v;
    },
    saveTaskListener(v) {
      this.taskListenerLength = v;
    },

    handlehttpServiceParamsAdd() {
      ScriptEditor.open(
        {
          title: "添加参数",
          language: "json",
          autoClose: false,
          content: jsonFormat(JSON.parse(this.formData.httpServiceParams), {
            type: "space",
            size: 4,
          }),
        },
        (data) => {
          const { content } = data;
          let jsonStr;
          try {
            jsonStr = JSON.parse(content);
          } catch (err) {
            this.$message.error("语法错误");
            return false;
          }
          this.$set(
            this.formData,
            "httpServiceParams",
            JSON.stringify(jsonStr)
          );
          ScriptEditor.close();
        }
      );
    },
    createPageTreeNode(tree) {
      return lodash.cloneDeep(tree).map((node) => {
        node.disabled = node.type === "folder";
        if (node.pageResults) {
          node.id = "folder" + node.id;
          node.children = node.pageResults || [];
          node.children.forEach((item) => {
            item.__formKey__ = `${item.key}`;
            item.name = `${item.name}（${item.key}）`;
          });
        }
        return node;
      });
    },
    // 脚本调试
    handleDebugScript(id = undefined) {
      console.log(id)
      const { origin, pathname } = window.location;
      window.open(
        `${origin}${pathname}#/scriptDebug?scriptId=${
          id ? id : this.formData.scriptId
        }`
      );
    },
    handleDebugScriptByCode(code) {
      const {origin, pathname} = window.location;
      window.open(`${origin}${pathname}#/scriptDebug?scriptCode=${code}`);
    },
    getTabRes() {
      const obj = {BASE: "基础"};
      const {showConfig} = this;
      if (showConfig.formKey) {
        obj.FORM = "表单";
      }
      if (showConfig.userSetting) {
        obj.NOTICE = "通知";
      }
      if (
        this.elementType === "bpmn:UserTask" &&
        this.element.id !== "__initiator__"
      ) {
        // 用户任务
        obj.EVENT = "事件";
      }
      this.tabList = obj;
    },
    formKeyValidator(rule, value, callback) {
      if (!this.formData.formKey && !this.formData.appFormKey) {
        callback(new Error("请选择待办表单"));
      } else {
        callback();
      }
    },
    formViewValidator(rule, value, callback) {
      if (!this.formData.formView && !this.formData.appFormView) {
        callback(new Error("请选择待查看表单"));
      } else {
        callback();
      }
    },
    // 参数配置
    configParam(paramType) {
      const params = this.formData[paramType] || '{}'
      this.$refs.ParamConfigModal.showModal(params, paramType)
    },
    setParamConfig(data, paramType = 'todoParams') {
      const payLoad = {}
      payLoad[paramType] = data ? String(data) : "",
        setFields(this.modeler, this.element, payLoad);
      this.$set(this.formData, paramType, data);
    }
  },
};
</script>

<style lang="scss" scoped>
.script-input-content {
  display: block;
  white-space: pre;
  line-height: 1.5em;
  border: 1px solid #dcdfe6;
  padding: 5px 10px;
  color: #666;
  border-radius: 4px;
}

.service-task {
  &_http-service {
    width: 35%;

    ::v-deep .el-input__inner {
      border-bottom-right-radius: 0;
      border-top-right-radius: 0;
      border-right: none;
    }

    ::v-deep .el-input.is-focus .el-input__inner,
    ::v-deep .el-input .el-input__inner:focus {
      border-color: #dcdfe6;
    }
  }

  &_service-path {
    flex: 1;

    ::v-deep .el-input__inner {
      border-bottom-left-radius: 0;
      border-top-left-radius: 0;
    }
  }
}

.custome-set-required ::v-deep > .el-form-item__label:before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

.condition-item ::v-deep .el-form-item__content {
  display: inline-block;
  width: calc(100% - 85px);
}
</style>
